package info.ask4research.web;

import info.ask4research.model.FileUploadBean;
import info.ask4research.model.Graph;
import info.ask4research.model.UnitOfLearning;
import info.ask4research.model.User;
import info.ask4research.model.activities.Activity;
import info.ask4research.model.activities.LearningActivity;
import info.ask4research.model.activities.SupportActivity;
import info.ask4research.model.enums.FinishingActivity;
import info.ask4research.model.enums.ResourceType;
import info.ask4research.model.roles.Role;
import info.ask4research.model.toolsAndMaterials.AnnouncementService;
import info.ask4research.model.toolsAndMaterials.ChatService;
import info.ask4research.model.toolsAndMaterials.ForumService;
import info.ask4research.model.toolsAndMaterials.LearningObject;
import info.ask4research.model.toolsAndMaterials.SentMailService;
import info.ask4research.model.toolsAndMaterials.ToolAndMaterial;
import info.ask4research.service.IActivityService;
import info.ask4research.service.IFileUploadBeanService;
import info.ask4research.service.IGraphService;
import info.ask4research.service.IRoleService;
import info.ask4research.service.IToolAndMaterialService;
import info.ask4research.service.IUnitOfLearningService;
import info.ask4research.service.impl.UserService;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.sun.org.apache.xpath.internal.XPathAPI;

@Controller
public class FileUploadController  {


	private IFileUploadBeanService fileUploadBeanService;
	private IUnitOfLearningService unitOfLearningService;
	private IActivityService activityService;
	private UserService userService;
	private IRoleService roleService;
	private IGraphService graphService;
	private IToolAndMaterialService toolAndMaterialService;

	public static List<String> langStrings = new ArrayList<String>();
	public static HashMap<String,String> learnerRoles = new HashMap<String,String>();
	public static HashMap<String,String> staffRoles = new HashMap<String,String>();
	public static HashMap<String,String> titleActivities = new HashMap<String,String>();
	public static HashMap<String,HashMap<String,Object>> activities = new HashMap<String,HashMap<String,Object>>();
	public static HashMap<String,HashMap<String,Object>> structuredActivities = new HashMap<String,HashMap<String,Object>>();
	public static HashMap<String,HashMap<String,Object>> environments = new HashMap<String,HashMap<String,Object>>();
	public static HashMap<String,HashMap<String,Object>> resources = new HashMap<String,HashMap<String,Object>>();
	public static HashMap<String,HashMap<String,Object>> acts = new HashMap<String,HashMap<String,Object>>();
	public static HashMap<String,HashMap<String,String>> actsOrdered = new HashMap<String,HashMap<String,String>>();
	public static LinkedList<String> linkedList = new LinkedList<String>();
	static XPath  xPath;
	static Document xmlDocument;


	static String titleXPath = "manifest//organizations//learning-design/title";

	static String learnersXPath = "manifest//organizations//learning-design/components/roles/learner";
	static String learnersTitleXPath = "manifest//organizations//learning-design/components/roles/learner/title";
	static String staffXPath = "manifest//organizations//learning-design/components/roles/staff";
	static String staffsTitleXPath = "manifest//organizations//learning-design/components/roles/staff/title";

	static String learningActivityXPath = "manifest//organizations//learning-design/components/activities/learning-activity";

	static String supportActivityXPath = "manifest//organizations//learning-design/components/activities/support-activity";

	static String activityStructureXPath = "manifest//organizations//learning-design/components/activities/activity-structure";

	static String environmentsXPath = "manifest//organizations//learning-design/components/environments/environment";

	static String playXPath = "manifest//organizations//learning-design/method/play/act/role-part";

	static String resourcesXPath = "manifest//resources/resource";

	static String learningActivityEnvironmentXPath = "manifest//organizations//learning-design/components/activities/learning-activity/environment-ref";

	@RequestMapping(value="jsp/fileUpload/importLD.action" , method = RequestMethod.POST)
	protected @ResponseBody boolean onSubmitImportLD(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value="file") CommonsMultipartFile command,
			HttpSession session) throws ServletException, IOException, SAXException, ParserConfigurationException, TransformerException {


		CommonsMultipartFile cmf = (CommonsMultipartFile)command;
		String fileName = cmf.getFileItem().getName();
		HashMap<String, FileUploadBean> fileUploadBeansResources = new HashMap<String, FileUploadBean>();
		if(fileName.endsWith(".zip")){
			ZipInputStream zis = new ZipInputStream(new BufferedInputStream(cmf.getInputStream()));
			ZipEntry entry;
			boolean imsmanifestExists = false;
			String imsManifestContent = null;
			String content = "";
			while ((entry = zis.getNextEntry()) != null) {
				System.out.println("Unzipping: " + entry.getName());
				
				if(entry.getName().equalsIgnoreCase("imsmanifest.xml")){
					imsmanifestExists = true;
					int size;
					byte[] buffer = new byte[2048];
					FileOutputStream fos = new FileOutputStream(entry.getName());
					BufferedOutputStream bos = new BufferedOutputStream(fos, buffer.length);
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
					while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
						bos.write(buffer, 0, size);
						baos.write(buffer, 0, size);
					}
					content = baos.toString("UTF-8");
					//System.out.println("ARXIGOS   "+content);
					bos.flush();
					bos.close();

					imsManifestContent = new String(bos.toString());
					// System.out.println(imsManifestContent);
				}else if(entry.getName().contains("\\")){
					int size;
					String[] title = entry.getName().split("\\\\");
					byte[] buffer = new byte[2048];
					FileOutputStream fos = new FileOutputStream(title[title.length-1]);
					BufferedOutputStream bos = new BufferedOutputStream(fos, buffer.length);
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
					while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
						bos.write(buffer, 0, size);
						baos.write(buffer, 0, size);
					}
					FileUploadBean fileUploadBean = new FileUploadBean();
					fileUploadBean.setBytes(baos.toByteArray());
					fileUploadBean.setName(title[title.length-1]);
					fileUploadBean.setSize(baos.size());
					fileUploadBeansResources.put(title[title.length-1], fileUploadBean);
				}else {
					int size;
					byte[] buffer = new byte[2048];
					FileOutputStream fos = new FileOutputStream(entry.getName());
					BufferedOutputStream bos = new BufferedOutputStream(fos, buffer.length);
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
					while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
						bos.write(buffer, 0, size);
						baos.write(buffer, 0, size);
					}
					FileUploadBean fileUploadBean = new FileUploadBean();
					fileUploadBean.setBytes(baos.toByteArray());
					fileUploadBean.setName(entry.getName());
					fileUploadBean.setSize(baos.size());
					fileUploadBeansResources.put(entry.getName(), fileUploadBean);
				}
			}
			zis.close();
			if(imsmanifestExists){
				Document doc = null;
				DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
				DocumentBuilder db = dbf.newDocumentBuilder();
				String s = imsManifestContent.toString();
				//System.out.println("ssss "+content);
				content = content.trim().replaceFirst("^([\\W]+)<","<");
				doc = db.parse(fromStringToInpuStream(content));
				ZipInputStream zis1 = new ZipInputStream(new BufferedInputStream(cmf.getInputStream()));

				importLD(doc, session, zis1, fileUploadBeansResources);

				return true;
			}
			return false;
		} else {
			return false;
		}

	}    

	public InputStream fromStringToInpuStream(String str)
	{
		InputStream is = new ByteArrayInputStream(str.getBytes());
		return is;
	}


	public void importLD(Document doc, HttpSession session, ZipInputStream zis1, HashMap<String, FileUploadBean> fileUploadBeansResources)
			throws TransformerException, FileNotFoundException, IOException, ParserConfigurationException{
		User user = userService.get((Integer)session.getAttribute("loginId"));

		NodeList generalList = doc.getElementsByTagName("langstring");

		for( int i = 0 ; i<generalList.getLength(); i++){
			Node node = generalList.item(0).getFirstChild();
			System.out.println(node.getNodeValue());
		}

		NodeList titleList = XPathAPI.selectNodeList(doc, titleXPath);
		Node nodeTitle = titleList.item(0);
		String title  = nodeTitle.getTextContent();

		xPath =  XPathFactory.newInstance().	newXPath();

		readRoles(doc);

		readLearningActivities(doc);

		readSupportActivities(doc);

		readStructuredActivities(doc);

		readEnvironment(doc);

		readPlay(doc);

		readResources(doc, fileUploadBeansResources);

		UnitOfLearning unitOfLearning = new UnitOfLearning();
		boolean exist = unitOfLearningService.existByTitle(title);
		int count = 0;
		String newTitle = "";
		while(exist){
			count++;
			newTitle = title+count;
			exist = unitOfLearningService.existByTitle(newTitle);
		}
		if(!exist && !"".equals(newTitle)){
			unitOfLearning.setTitle(newTitle);
			unitOfLearning.setSubject(newTitle);
			unitOfLearning.setAuthor(user);
			unitOfLearning.setDescription(newTitle);
			unitOfLearning = unitOfLearningService.create(unitOfLearning);
			session.setAttribute("unitOfLearningId", unitOfLearning.getId());
		} else {
			unitOfLearning.setTitle(title);
			unitOfLearning.setSubject(title);
			unitOfLearning.setAuthor(user);
			unitOfLearning.setDescription(title);
			unitOfLearning = unitOfLearningService.create(unitOfLearning);
			session.setAttribute("unitOfLearningId", unitOfLearning.getId());
		}


		HashMap<String,Role> savedUsers = new HashMap<String,Role>();

		Set<String> keysS  = staffRoles.keySet();
		Iterator staffIt = keysS.iterator();
		while(staffIt.hasNext()){
			String roleRef = (String) staffIt.next();
			Role staff = new Role();
			staff.setText((String)staffRoles.get(roleRef));
			staff.setStaffRole(true);
			staff.setLearnerRole(false);
			staff.setUnitOfLearning(unitOfLearning);
			staff = roleService.save(staff);
			savedUsers.put(roleRef, staff);
		}

		Set<String> keysL  = learnerRoles.keySet();
		Iterator learnersIt = keysL.iterator();
		while(learnersIt.hasNext()){
			String roleRef = (String) learnersIt.next();
			Role learner = new Role();
			learner.setText((String)learnerRoles.get(roleRef));
			learner.setStaffRole(false);
			learner.setLearnerRole(true);
			learner.setUnitOfLearning(unitOfLearning);
			learner = roleService.save(learner);
			savedUsers.put(roleRef, learner);
		}

		HashMap<String,ToolAndMaterial> savedTams = new HashMap<String,ToolAndMaterial>();
		Set<String> environmentsTams = environments.keySet();
		Iterator environmentsTamsIt = environmentsTams.iterator();
		while(environmentsTamsIt.hasNext()){
			String envKey = (String) environmentsTamsIt.next();
			HashMap<String,Object> hashTams = (HashMap<String, Object>) environments.get(envKey);
			String type = (String) hashTams.get("type");
			if("LO".equals(type)){
				LearningObject lo = new LearningObject();
				lo.setTitle((String)hashTams.get("title"));	
				if(!StringUtils.isEmpty((String)hashTams.get("descItemRef"))){
					HashMap<String,Object> attributes = resources.get((String)hashTams.get("descItemRef"));
					FileUploadBean fBean = (FileUploadBean)attributes.get("file");
					byte[] b = fBean.getBytes();
					String s = new String(b);
					lo.setDescription(s);
				}else{
					lo.setDescription("Please Define a Description");
				}
				lo.setUnitOfLearning(unitOfLearning);
				lo = (LearningObject) toolAndMaterialService.save(lo);
				savedTams.put(envKey, lo);
			}else if("asynchronous".equals(type)){
				ForumService fs = new ForumService();
				fs.setTitle((String)hashTams.get("title"));					
				if(!StringUtils.isEmpty((String)hashTams.get("descItemRef"))){
					HashMap<String,Object> attributes = resources.get((String)hashTams.get("descItemRef"));
					FileUploadBean fBean = (FileUploadBean)attributes.get("file");
					byte[] b = fBean.getBytes();
					String s = new String(b);
					fs.setDescription(s);
				}else{
					fs.setDescription("Please Define a Description");
				}
				fs.setManager(savedUsers.get("conferenceManager"));
				fs.setModerator(savedUsers.get("moderator"));
				fs.setUnitOfLearning(unitOfLearning);
				fs = (ForumService) toolAndMaterialService.save(fs);
				savedTams.put(envKey, fs);
			}else if("synchronous".equals(type)){
				ChatService cs = new ChatService();
				cs.setTitle((String)hashTams.get("title"));					
				if(!StringUtils.isEmpty((String)hashTams.get("descItemRef"))){
					HashMap<String,Object> attributes = resources.get((String)hashTams.get("descItemRef"));
					FileUploadBean fBean = (FileUploadBean)attributes.get("file");
					byte[] b = fBean.getBytes();
					String s = new String(b);
					cs.setDescription(s);
				}else{
					cs.setDescription("Please Define a Description");
				}
				cs.setManager(savedUsers.get("conferenceManager"));
				cs.setModerator(savedUsers.get("moderator"));
				cs.setUnitOfLearning(unitOfLearning);
				cs = (ChatService) toolAndMaterialService.save(cs);
				savedTams.put(envKey, cs);
			}else if("announcement".equals(type)){
				AnnouncementService as = new AnnouncementService();
				as.setTitle((String)hashTams.get("title"));					
				if(!StringUtils.isEmpty((String)hashTams.get("descItemRef"))){
					HashMap<String,Object> attributes = resources.get((String)hashTams.get("descItemRef"));
					FileUploadBean fBean = (FileUploadBean)attributes.get("file");
					byte[] b = fBean.getBytes();
					String s = new String(b);
					as.setDescription(s);
				}else{
					as.setDescription("Please Define a Description");
				}
				as.setManager(savedUsers.get("conferenceManager"));
				as.setModerator(savedUsers.get("moderator"));
				as.setUnitOfLearning(unitOfLearning);
				as = (AnnouncementService) toolAndMaterialService.save(as);
				savedTams.put(envKey, as);
			}else if("send-mail".equals(type)){
				SentMailService sm = new SentMailService();
				sm.setTitle((String)hashTams.get("title"));					
				if(!StringUtils.isEmpty((String)hashTams.get("descItemRef"))){
					HashMap<String,Object> attributes = resources.get((String)hashTams.get("descItemRef"));
					FileUploadBean fBean = (FileUploadBean)attributes.get("file");
					byte[] b = fBean.getBytes();
					String s = new String(b);
					sm.setDescription(s);
				}else{
					sm.setDescription("Please Define a Description");
				}
				sm.setUnitOfLearning(unitOfLearning);
				sm = (SentMailService) toolAndMaterialService.save(sm);
				savedTams.put(envKey, sm);
			}

		}

		environments.clear();
		
		Set<String> activityKeys = activities.keySet();
		Iterator it = activityKeys.iterator();
		while(it.hasNext()){
			String activityKey = (String) it.next();
			HashMap<String,Object> activityAttributes = activities.get(activityKey);
			if(activityAttributes.containsKey("LearningActivity")){
				LearningActivity learningActivity = new LearningActivity();
				//get the autor
				HashMap<String,String> attributes = actsOrdered.get(activityKey);
				if(attributes != null){
					String roleAuthorRef = attributes.get("role");
					//String laID = attributes.get("learning");
					learningActivity.setAuthor(savedUsers.get(roleAuthorRef));
					learningActivity.setActivityGraphId(activityKey);
					List<ToolAndMaterial> tamsAttachToUoL =  new ArrayList<ToolAndMaterial>();
					List<String> environmentList  = (List<String>) activityAttributes.get("environments");
					for( int j = 0; j<environmentList.size(); j++){
						String envId = environmentList.get(j);
						tamsAttachToUoL.add(savedTams.get(envId));
					}
					learningActivity.setTams(tamsAttachToUoL);
					List<String> descrfiles = (List<String>) activityAttributes.get("descItemRef");
					if(!descrfiles.isEmpty()){
						for(String s : descrfiles){
							HashMap<String,Object> attributes1 = resources.get(s);
							FileUploadBean fBean = (FileUploadBean)attributes1.get("file");
							fBean.setResourceType(ResourceType.LADESCRIPTION);
							fBean = fileUploadBeanService.save(fBean);
							learningActivity.addFiles(fBean);
						}
						
					}
					learningActivity.setDescription((String)activityAttributes.get("descTitle"));
					String completeActivity = (String)activityAttributes.get("completeActivity");
					if("none".equals(completeActivity)){
						learningActivity.setFinishingActivity(FinishingActivity.NONE);
					}else if ("userChoice".equals(completeActivity)){
						learningActivity.setFinishingActivity(FinishingActivity.USERCHOICE);
					} else {
						learningActivity.setFinishingActivity(FinishingActivity.TIMELIMIT);
						learningActivity.setTimeLimit((String)activityAttributes.get("completeActivity"));
					}
					
					learningActivity = (LearningActivity) activityService.save(learningActivity);
					unitOfLearning.addActivity(learningActivity);
					unitOfLearningService.save(unitOfLearning);
				} 
			}
			else if(activityAttributes.containsKey("SupportActivity")) {
				SupportActivity supportActivity = new SupportActivity();
				//get the autor
				HashMap<String,String> attributes = actsOrdered.get(activityKey);
				
				if(attributes != null){
					String roleAuthorRef = attributes.get("role");
					//String saID = attributes.get("support");
					supportActivity.setAuthor(savedUsers.get(roleAuthorRef));
					supportActivity.setActivityGraphId(activityKey);
					List<ToolAndMaterial> tamsAttachToUoL =  new ArrayList<ToolAndMaterial>();
					List<String> environmentList  = (List<String>) activityAttributes.get("environments");
					for( int j = 0; j<environmentList.size(); j++){
						String envId = environmentList.get(j);
						tamsAttachToUoL.add(savedTams.get(envId));
					}
					List<String> descrfiles = (List<String>) activityAttributes.get("descItemRef");
					if(!descrfiles.isEmpty()){
						for(String s : descrfiles){
							HashMap<String,Object> attributes1 = resources.get(s);
							FileUploadBean fBean = (FileUploadBean)attributes1.get("file");
							fBean.setResourceType(ResourceType.SADESCRIPTION);
							fBean = fileUploadBeanService.save(fBean);
							supportActivity.addFiles(fBean);
						}
						
					}
					supportActivity.setTams(tamsAttachToUoL);
					supportActivity.setDescription((String)activityAttributes.get("descTitle"));
					String completeActivity = (String)activityAttributes.get("completeActivity");
					if("none".equals(completeActivity)){
						supportActivity.setFinishingActivity(FinishingActivity.NONE);
					}else if ("userChoice".equals(completeActivity)){
						supportActivity.setFinishingActivity(FinishingActivity.USERCHOICE);
					} else {
						supportActivity.setFinishingActivity(FinishingActivity.TIMELIMIT);
						supportActivity.setTimeLimit((String)activityAttributes.get("completeActivity"));
					}
	
					supportActivity = (SupportActivity) activityService.save(supportActivity);
					unitOfLearning.addActivity(supportActivity);
					unitOfLearningService.save(unitOfLearning);
				}
			}

		}
		createXMLDiagram(linkedList, unitOfLearning);
		actsOrdered.clear();
		activities.clear();
		linkedList.clear();
		System.out.println("asdasd");
	}

	private void createXMLDiagram(LinkedList linkedList, UnitOfLearning unitOfLearning) throws ParserConfigurationException, TransformerException {
		String xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>";
		xml += "<form>";
		xml +="<Start x=\"20\" y=\"20\" id=\"42a070bf-f96c-1963-6a8c-1cc56835404c\"></Start>";
		List<String> orderString = new ArrayList<String>();
		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
 
		// root elements
		Document doc = docBuilder.newDocument();
		Element form = doc.createElement("form");
		doc.appendChild(form);
		
		Element start = doc.createElement("Start");
		form.appendChild(start);
		
		Attr attrX = doc.createAttribute("x");
		attrX.setValue("10");
		start.setAttributeNode(attrX);
		
		Attr attrY = doc.createAttribute("y");
		attrY.setValue("10");
		start.setAttributeNode(attrY);
		
		SecureRandom random = new SecureRandom();
		String bi = new BigInteger(130, random).toString(32);
		
		Attr attrID = doc.createAttribute("id");
		attrID.setValue(bi);
		start.setAttributeNode(attrID);
		orderString.add(bi);
		for(int i = 0; i< linkedList.size(); i++){
			String diagramId = (String) linkedList.get(i);
			int x = i*80;
			int y = i*80;
			if(i==0){
				x = 40;
				y = 40;
			}
			
			if(diagramId.startsWith("Learning") || diagramId.startsWith("Support")){
				String[] object = diagramId.split(":");
				if("Support".equals(object[0])){
					
					Element supportActivity = doc.createElement("SupportActivity");
					form.appendChild(supportActivity);
					
					Attr supportActivityAttrX = doc.createAttribute("x");
					supportActivityAttrX.setValue(String.valueOf(x));
					supportActivity.setAttributeNode(supportActivityAttrX);
					
					Attr supportActivityAttrY = doc.createAttribute("y");
					supportActivityAttrY.setValue(String.valueOf(y));
					supportActivity.setAttributeNode(supportActivityAttrY);
					
					Attr supportActivityAttrID = doc.createAttribute("id");
					supportActivityAttrID.setValue(object[1]);
					supportActivity.setAttributeNode(supportActivityAttrID);
					orderString.add(object[1]);
				}else if("Learning".equals(object[0])){
					
					Element activity = doc.createElement("Activity");
					form.appendChild(activity);
					
					Attr activityAttrX = doc.createAttribute("x");
					activityAttrX.setValue(String.valueOf(x));
					activity.setAttributeNode(activityAttrX);
					
					Attr activityAttrY = doc.createAttribute("y");
					activityAttrY.setValue(String.valueOf(y));
					activity.setAttributeNode(activityAttrY);
					
					Attr activityAttrID = doc.createAttribute("id");
					activityAttrID.setValue(object[1]);
					activity.setAttributeNode(activityAttrID);
					orderString.add(object[1]);
				}
			}else if("Split".equals(diagramId)){
				
				Element oneToTwo = doc.createElement("OneToTwo");
				form.appendChild(oneToTwo);
				
				Attr oneToTwoAttrX = doc.createAttribute("x");
				oneToTwoAttrX.setValue(String.valueOf(x));
				oneToTwo.setAttributeNode(oneToTwoAttrX);
				
				Attr oneToTwoAttrY = doc.createAttribute("y");
				oneToTwoAttrY.setValue(String.valueOf(y));
				oneToTwo.setAttributeNode(oneToTwoAttrY);
				
				String splitId = new BigInteger(130, random).toString(32);
				
				Attr oneToTwoAttrID = doc.createAttribute("id");
				oneToTwoAttrID.setValue(splitId);
				oneToTwo.setAttributeNode(oneToTwoAttrID);
				orderString.add("ss:"+splitId);
			}else if("Merge".equals(diagramId)){
				
				Element oneToTwo = doc.createElement("TwoToOne");
				form.appendChild(oneToTwo);
				
				Attr oneToTwoAttrX = doc.createAttribute("x");
				oneToTwoAttrX.setValue(String.valueOf(x));
				oneToTwo.setAttributeNode(oneToTwoAttrX);
				
				Attr oneToTwoAttrY = doc.createAttribute("y");
				oneToTwoAttrY.setValue(String.valueOf(y));
				oneToTwo.setAttributeNode(oneToTwoAttrY);
				String mergeId = new BigInteger(130, random).toString(32);
				Attr oneToTwoAttrID = doc.createAttribute("id");
				oneToTwoAttrID.setValue(mergeId);
				oneToTwo.setAttributeNode(oneToTwoAttrID);
				orderString.add("mm:"+mergeId);
			}
		}
		Element exit = doc.createElement("Exit");
		form.appendChild(exit);
		
		Attr exitX = doc.createAttribute("x");
		exitX.setValue("10");
		exit.setAttributeNode(exitX);
		
		Attr exitY = doc.createAttribute("y");
		exitY.setValue("300");
		exit.setAttributeNode(exitY);
		String exitId = new BigInteger(130, random).toString(32);
		Attr exitID = doc.createAttribute("id");
		exitID.setValue(exitId);
		exit.setAttributeNode(exitID);
		orderString.add(exitId);
		List<String> splitNodes = new ArrayList<String>();
		int countSplits = 0;
		
		Iterator<String> it = orderString.iterator();
		
		while(it.hasNext()){
			String node = it.next();
			if(node.startsWith("ss:")){
				while(!node.startsWith("mm:") && it.hasNext()){
					node = it.next();
					if(!node.startsWith("mm:")){
						splitNodes.add(node);
					}
					
				}
			}
		}
		
		for(int k = 0 ; k<orderString.size(); k++){
			System.out.println(orderString.get(k));
			String objId = orderString.get(k);
			if(k<orderString.size()-1){
				if(objId.startsWith("mm:")){
					objId = objId.substring(3);
					
					for(int j = 0; j<splitNodes.size(); j++){
						Element connection = doc.createElement("Connection");
						form.appendChild(connection);
						
						String sourceParentNodeId = splitNodes.get(j);
						
						Attr sourceParentNodeIdAttr = doc.createAttribute("sourceParentNodeId");
						sourceParentNodeIdAttr.setValue(sourceParentNodeId);
						connection.setAttributeNode(sourceParentNodeIdAttr);
						
						Attr targetParentNodeIdAttr = doc.createAttribute("targetParentNodeId");
						targetParentNodeIdAttr.setValue(objId);
						connection.setAttributeNode(targetParentNodeIdAttr);
					}
					Element connection = doc.createElement("Connection");
					form.appendChild(connection);
					
					String sourceParentNodeId = orderString.get(k);
					if(sourceParentNodeId.startsWith("ss:") || sourceParentNodeId.startsWith("mm:")){
						sourceParentNodeId = sourceParentNodeId.substring(3);
					}
					String targetParentNodeId = orderString.get(k+1);
					if(targetParentNodeId.startsWith("ss:") || targetParentNodeId.startsWith("mm:")){
						targetParentNodeId = targetParentNodeId.substring(3);
					}
					Attr sourceParentNodeIdAttr = doc.createAttribute("sourceParentNodeId");
					sourceParentNodeIdAttr.setValue(sourceParentNodeId);
					connection.setAttributeNode(sourceParentNodeIdAttr);
					
					Attr targetParentNodeIdAttr = doc.createAttribute("targetParentNodeId");
					targetParentNodeIdAttr.setValue(targetParentNodeId);
					connection.setAttributeNode(targetParentNodeIdAttr);
					
				} else if(!objId.startsWith("ss:")){
					Element connection = doc.createElement("Connection");
					form.appendChild(connection);
					
					String sourceParentNodeId = orderString.get(k);
					if(sourceParentNodeId.startsWith("ss:") || sourceParentNodeId.startsWith("mm:")){
						sourceParentNodeId = sourceParentNodeId.substring(3);
					}
					String targetParentNodeId = orderString.get(k+1);
					if(targetParentNodeId.startsWith("ss:") || targetParentNodeId.startsWith("mm:")){
						targetParentNodeId = targetParentNodeId.substring(3);
					}
					Attr sourceParentNodeIdAttr = doc.createAttribute("sourceParentNodeId");
					sourceParentNodeIdAttr.setValue(sourceParentNodeId);
					connection.setAttributeNode(sourceParentNodeIdAttr);
					
					Attr targetParentNodeIdAttr = doc.createAttribute("targetParentNodeId");
					targetParentNodeIdAttr.setValue(targetParentNodeId);
					connection.setAttributeNode(targetParentNodeIdAttr);
					
				}
				
				else {
					objId = objId.substring(3);
					for(int j = 0; j<splitNodes.size(); j++){
						
						
						Element connection = doc.createElement("Connection");
						form.appendChild(connection);
						
						
						String targetParentNodeId = splitNodes.get(j);
						
						Attr sourceParentNodeIdAttr = doc.createAttribute("sourceParentNodeId");
						sourceParentNodeIdAttr.setValue(objId);
						connection.setAttributeNode(sourceParentNodeIdAttr);
						
						Attr targetParentNodeIdAttr = doc.createAttribute("targetParentNodeId");
						targetParentNodeIdAttr.setValue(targetParentNodeId);
						connection.setAttributeNode(targetParentNodeIdAttr);
					}
					
					k = k + splitNodes.size();
				}
			}
		}
		
		
		
		
		StreamResult result = new StreamResult(new StringWriter());
		DOMSource source = new DOMSource(doc);
		javax.xml.transform.Transformer transformer = TransformerFactory.newInstance().newTransformer();
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");

		transformer.transform(source, result);
		String xmlString = result.getWriter().toString();
		System.out.println(xmlString);

		Graph graph = new Graph();
		graph.setGraphHtml(xmlString);
		graph = graphService.save(graph);
		unitOfLearning.setGraph(graph);
		unitOfLearningService.save(unitOfLearning);
	}

	private void readRoles(Document doc) throws TransformerException {
		NodeList learnersList = XPathAPI.selectNodeList(doc, learnersXPath);
		for(int i=0;i<learnersList.getLength(); i++){
			Node node = learnersList.item(i);
			NamedNodeMap namedNodeMap = node.getAttributes();
			String startId = namedNodeMap.getNamedItem("identifier").getTextContent();
			String titleValue = XPathAPI.selectNodeList(doc, learnersTitleXPath).item(0).getFirstChild().getNodeValue();
			if("Learner".equalsIgnoreCase(titleValue)){
				titleValue=titleValue+"1";
			}
			learnerRoles.put(startId, titleValue);
		}

		NodeList staffList = XPathAPI.selectNodeList(doc, staffXPath);
		for(int i=0;i<staffList.getLength(); i++){
			Node node = staffList.item(i);
			NamedNodeMap namedNodeMap = node.getAttributes();
			String startId = namedNodeMap.getNamedItem("identifier").getTextContent();
			String titleValue = XPathAPI.selectNodeList(doc, staffsTitleXPath).item(0).getFirstChild().getNodeValue();
			if("Staff".equalsIgnoreCase(titleValue)){
				titleValue=titleValue+"1";
			}
			staffRoles.put(startId, titleValue);
		}
	}

	private void readLearningActivities(Document doc)
			throws TransformerException {
		NodeList learningActivitiesList = XPathAPI.selectNodeList(doc, learningActivityXPath);
		for(int i=0;i<learningActivitiesList.getLength(); i++){
			Node node = learningActivitiesList.item(i);
			NamedNodeMap namedNodeMap = node.getAttributes();
			String startId = namedNodeMap.getNamedItem("identifier").getTextContent();
			NodeList nodes = node.getChildNodes();
			HashMap<String,Object> attributes = new HashMap<String,Object>();
			List<String> environments = new ArrayList<String>();
			String descTitle = "";
			String descItemRef = "";
			String descItemTitle = "";
			String completeActivity = "";
			List<String> descrItemRef = new ArrayList<String>();
			for(int j = 0; j<nodes.getLength(); j++){
				Node innerNode = nodes.item(j);
				if("imsld:environment-ref".equals(innerNode.getNodeName())){
					NamedNodeMap envAttrs = innerNode.getAttributes();
					String ref = envAttrs.getNamedItem("ref").getTextContent();
					environments.add(ref);
				}else if("imsld:activity-description".equals(innerNode.getNodeName())){
					NodeList descs = innerNode.getChildNodes();
					for(int k = 0; k<descs.getLength(); k++){
						Node desc = descs.item(k);
						if("imsld:title".equals(desc.getNodeName())){
							descTitle = desc.getTextContent();
						}else if("imsld:item".equals(desc.getNodeName())){
							NamedNodeMap envAttrs = desc.getAttributes();
							String ref = envAttrs.getNamedItem("identifierref").getTextContent();
							descItemRef = ref;
							Node descItemTitleNode = desc.getChildNodes().item(0).getNextSibling();
							descItemTitle = descItemTitleNode.getFirstChild().getNodeValue();
							descrItemRef.add(descItemRef);
						}
					}
				}else if("imsld:complete-activity".equals(innerNode.getNodeName())){
					NodeList descs = innerNode.getChildNodes();
					Node descItemTitleNode = descs.item(0);
					if(descs.getLength()==0){
						completeActivity = "none";
					}else  if(descs.getLength() > 0){
						if(descItemTitleNode.getNextSibling().getNodeName() == "imsld:user-choice"){
							completeActivity = "userChoice";
						}else{
							completeActivity = descItemTitleNode.getNextSibling().getFirstChild().getNodeValue();
						}
					}
				}
			}
			attributes.put("environments", environments);
			attributes.put("descTitle", descTitle);
			attributes.put("descItemRef", descrItemRef);
			attributes.put("descItemTitle", descItemTitle);
			attributes.put("completeActivity", completeActivity);
			attributes.put("LearningActivity", "LearningActivity");
			activities.put(startId, attributes);
		}
	}

	private void readSupportActivities(Document doc)
			throws TransformerException {
		NodeList supportActivitiesList = XPathAPI.selectNodeList(doc, supportActivityXPath);
		for(int i=0;i<supportActivitiesList.getLength(); i++){
			Node node = supportActivitiesList.item(i);
			NamedNodeMap namedNodeMap = node.getAttributes();
			String startId = namedNodeMap.getNamedItem("identifier").getTextContent();
			NodeList nodes = node.getChildNodes();
			HashMap<String,Object> attributes = new HashMap<String,Object>();
			List<String> environments = new ArrayList<String>();
			List<String> roles = new ArrayList<String>();
			String descTitle = "";
			String descItemRef = "";
			String descItemTitle = "";
			String completeActivity = "";
			List<String> descrItemRef = new ArrayList<String>();
			for(int j = 0; j<nodes.getLength(); j++){
				Node innerNode = nodes.item(j);
				if("imsld:environment-ref".equals(innerNode.getNodeName())){
					NamedNodeMap envAttrs = innerNode.getAttributes();
					String ref = envAttrs.getNamedItem("ref").getTextContent();
					environments.add(ref);
				}else if("imsld:role-ref".equals(innerNode.getNodeName())){
					NamedNodeMap envAttrs = innerNode.getAttributes();
					String ref = envAttrs.getNamedItem("ref").getTextContent();
					roles.add(ref);
				}else if("imsld:activity-description".equals(innerNode.getNodeName())){
					NodeList descs = innerNode.getChildNodes();
					for(int k = 0; k<descs.getLength(); k++){
						Node desc = descs.item(k);
						if("imsld:title".equals(desc.getNodeName())){
							descTitle = desc.getTextContent();
						}else if("imsld:item".equals(desc.getNodeName())){
							NamedNodeMap envAttrs = desc.getAttributes();
							String ref = envAttrs.getNamedItem("identifierref").getTextContent();
							descItemRef = ref;
							Node descItemTitleNode = desc.getChildNodes().item(0).getNextSibling();
							descItemTitle = descItemTitleNode.getFirstChild().getNodeValue();
							descrItemRef.add(descItemRef);
						}
					}
				}else if("imsld:complete-activity".equals(innerNode.getNodeName())){
					NodeList descs = innerNode.getChildNodes();
					Node descItemTitleNode = descs.item(0);
					if(descs.getLength()==0){
						completeActivity = "none";
					}else  if(descs.getLength() > 0){
						if(descItemTitleNode.getNextSibling().getNodeName() == "imsld:user-choice"){
							completeActivity = "userChoice";
						}else{
							completeActivity = descItemTitleNode.getNextSibling().getFirstChild().getNodeValue();
						}
					}
				}
			}
			attributes.put("environments", environments);
			attributes.put("roles", roles);
			attributes.put("descTitle", descTitle);
			attributes.put("descItemRef", descrItemRef);
			attributes.put("descItemTitle", descItemTitle);
			attributes.put("completeActivity", completeActivity);
			attributes.put("SupportActivity", "SupportActivity");
			activities.put(startId, attributes);
		}
	}

	private void readStructuredActivities(Document doc) throws TransformerException {
		NodeList activityStructureList = XPathAPI.selectNodeList(doc, activityStructureXPath);
		for(int i=0;i<activityStructureList.getLength(); i++){
			Node node = activityStructureList.item(i);
			NamedNodeMap namedNodeMap = node.getAttributes();
			String startId = namedNodeMap.getNamedItem("identifier").getTextContent();
			String structureType = namedNodeMap.getNamedItem("structure-type").getTextContent();
			NodeList nodes = node.getChildNodes();
			HashMap<String,Object> attributes = new HashMap<String,Object>();
			List<String> la = new ArrayList<String>();
			List<String> sa = new ArrayList<String>();
			for(int j = 0; j<nodes.getLength(); j++){
				Node innerNode = nodes.item(j);
				if("imsld:learning-activity-ref".equals(innerNode.getNodeName())){
					NamedNodeMap envAttrs = innerNode.getAttributes();
					String ref = envAttrs.getNamedItem("ref").getTextContent();
					la.add(ref);
				}else if("imsld:support-activity-ref".equals(innerNode.getNodeName())){
					NamedNodeMap envAttrs = innerNode.getAttributes();
					String ref = envAttrs.getNamedItem("ref").getTextContent();
					sa.add(ref);
				}
			}
			attributes.put("structureType", structureType);
			attributes.put("la", la);
			attributes.put("sa", sa);
			structuredActivities.put(startId, attributes);
		}
	}

	private void readEnvironment(Document doc) throws TransformerException {
		NodeList environmentList = XPathAPI.selectNodeList(doc, environmentsXPath);
		for(int i=0;i<environmentList.getLength(); i++){
			Node node = environmentList.item(i);
			NamedNodeMap namedNodeMap = node.getAttributes();
			String startId = namedNodeMap.getNamedItem("identifier").getTextContent();
			NodeList nodes = node.getChildNodes();
			HashMap<String,Object> attributes = new HashMap<String,Object>();
			List<String> environmentsList = new ArrayList<String>();
			List<String> roles = new ArrayList<String>();
			List<String> items = new ArrayList<String>();
			String titl = "";
			String descTitle = "";
			String descItemRef = "";
			String descItemTitle = "";
			String conferenceManager = "";
			String moderator = "";;
			String serviceTitle = "";
			String type = "";
			for(int j = 0; j<nodes.getLength(); j++){
				Node innerNode = nodes.item(j);
				if("imsld:title".equals(innerNode.getNodeName())){
					titl = innerNode.getChildNodes().item(0).getNodeValue();
				}else if("imsld:learning-object".equals(innerNode.getNodeName())){
					type = "LO";
					NodeList descs = innerNode.getChildNodes();
					for(int k = 0; k<descs.getLength(); k++){
						Node desc = descs.item(k);
						if("imsld:item".equals(desc.getNodeName())){
							NamedNodeMap envAttrs1 = desc.getAttributes();
							String ref1 = envAttrs1.getNamedItem("identifierref").getTextContent();
							descItemRef = ref1;
							Node descItemTitleNode = desc.getChildNodes().item(0).getNextSibling();
							descItemTitle = descItemTitleNode.getFirstChild().getNodeValue();
						}
					}
				}else if("imsld:service".equals(innerNode.getNodeName())){
					NodeList descs = innerNode.getChildNodes();
					for(int k = 0; k<descs.getLength(); k++){
						Node desc = descs.item(k);
						if("imsld:conference".equals(desc.getNodeName())){
							type = desc.getAttributes().getNamedItem("conference-type").getTextContent();
							NodeList otherNodes = desc.getChildNodes();
							for(int s = 0; s< otherNodes.getLength(); s++){
								Node desc1 = otherNodes.item(s);
								if("imsld:conference-manager".equals(desc1.getNodeName())){
									NamedNodeMap envAttrs1 = desc1.getAttributes();
									String ref1 = envAttrs1.getNamedItem("role-ref").getTextContent();
									conferenceManager = ref1;
								}else if("imsld:moderator".equals(desc1.getNodeName())){
									NamedNodeMap envAttrs1 = desc1.getAttributes();
									String ref1 = envAttrs1.getNamedItem("role-ref").getTextContent();
									moderator = ref1;
								}else if("imsld:item".equals(desc1.getNodeName())){
									NamedNodeMap envAttrs1 = desc1.getAttributes();
									String ref1 = envAttrs1.getNamedItem("identifierref").getTextContent();
									descItemRef = ref1;
									Node descItemTitleNode = desc1.getChildNodes().item(0).getNextSibling();
									descItemTitle = descItemTitleNode.getFirstChild().getNodeValue();
								}
							}
						} else if("imsld:send-mail".equals(desc.getNodeName())){
							type = "send-mail";
							NodeList otherNodes = desc.getChildNodes();
							serviceTitle = otherNodes.item(0).getNodeValue();
						}
					}
				}

			}
			attributes.put("title", titl);
			attributes.put("descTitle", descTitle);
			attributes.put("descItemRef", descItemRef);
			attributes.put("serviceTitle", serviceTitle);
			attributes.put("descItemTitle", descItemTitle);
			attributes.put("moderator", moderator);
			attributes.put("type", type);
			attributes.put("conferenceManager", conferenceManager);
			environments.put(startId, attributes);
		}
	}
	private void readPlay(Document doc) throws TransformerException {
		NodeList actsList = XPathAPI.selectNodeList(doc, playXPath);
		
		int structuredNodes = structuredActivities.size();
		
		for(int i=0;i<actsList.getLength(); i++){
			Node node = actsList.item(i);
			NodeList nodes = node.getChildNodes();
			HashMap<String,String> attributes = new HashMap<String,String>();
			for(int j = 0; j<nodes.getLength(); j++){
				Node innerNode = nodes.item(j);
				if("imsld:support-activity-ref".equals(innerNode.getNodeName())){
					NamedNodeMap saAttrs = innerNode.getAttributes();
					String ref = saAttrs.getNamedItem("ref").getTextContent();
					attributes.put("support", ref);
				}else if("imsld:learning-activity-ref".equals(innerNode.getNodeName())){
					NamedNodeMap envAttrs = innerNode.getAttributes();
					String ref = envAttrs.getNamedItem("ref").getTextContent();
					attributes.put("learning", ref);
				}else if("imsld:role-ref".equals(innerNode.getNodeName())){
					NamedNodeMap envAttrs = innerNode.getAttributes();
					String ref = envAttrs.getNamedItem("ref").getTextContent();
					attributes.put("role", ref);
				}
			}
			String supportId = attributes.get("support");
			String learningId = attributes.get("learning");
			if(!StringUtils.isEmpty(supportId) || !StringUtils.isEmpty(learningId)){
				if(structuredActivities.containsKey(supportId) || structuredActivities.containsKey(learningId)){
					linkedList.add("Split");
					if(!StringUtils.isEmpty(supportId)){
							HashMap<String, Object> hash = structuredActivities.get(supportId);
							if(hash.get("la") != null){
								System.out.println("contaions la");
								List<String> las = (List<String>) hash.get("la");
								for(String la : las){
									System.out.println("contaions laaaaaa" + la);
									actsOrdered.put(la, attributes);
									linkedList.add("Learning:"+la);
								}
							}
							if(hash.get("sa") != null){
								System.out.println("contaions sa");
								List<String> sas = (List<String>) hash.get("sa");
								for(String sa : sas){
									System.out.println("contaions saaaaaa" + sa);
									actsOrdered.put(sa, attributes);
									linkedList.add("Support:"+sa);
								}
							}
					}else{
						HashMap<String, Object> hash = structuredActivities.get(learningId);
						if(hash.get("la") != null){
							System.out.println("contaions la");
							List<String> las = (List<String>) hash.get("la");
							for(String la : las){
								System.out.println("contaions laaaaaa" + la);
								actsOrdered.put(la, attributes);
								linkedList.add("Learning:"+la);
							}
						}
						if(hash.get("sa") != null){
							System.out.println("contaions sa");
							List<String> sas = (List<String>) hash.get("sa");
							for(String sa : sas){
								System.out.println("contaions saaaaaa" + sa);
								actsOrdered.put(sa, attributes);
								linkedList.add("Support:"+sa);
							}
						}
					}
					
					linkedList.add("Merge");
				}else{
					if(!StringUtils.isEmpty(attributes.get("support"))){
						actsOrdered.put(attributes.get("support"), attributes);
						linkedList.add("Support:"+attributes.get("support"));
					}else if(!StringUtils.isEmpty(attributes.get("learning"))){
						actsOrdered.put(attributes.get("learning"), attributes);
						linkedList.add("Learning:"+attributes.get("learning"));
					}
					
				}
			} 
				
		}
		
	}

	private void readResources(Document doc, HashMap<String, FileUploadBean> fileUploadBeansResources) throws TransformerException, UnsupportedEncodingException {
		NodeList resourcesList = XPathAPI.selectNodeList(doc, resourcesXPath);
		for(int i=0;i<resourcesList.getLength(); i++){
			Node node = resourcesList.item(i);
			NamedNodeMap namedNodeMap = node.getAttributes();
			String type = namedNodeMap.getNamedItem("type").getTextContent();
			String identifier = namedNodeMap.getNamedItem("identifier").getTextContent();
			String ref = "";
			NodeList nodes = node.getChildNodes();
			HashMap<String,Object> attributes = new HashMap<String,Object>();
			for(int j = 0; j<nodes.getLength(); j++){
				Node innerNode = nodes.item(j);
				if("imscp:file".equals(innerNode.getNodeName())){
					NamedNodeMap envAttrs = innerNode.getAttributes();
					ref = envAttrs.getNamedItem("href").getTextContent();
					if(ref.contains("/")){
						String[] title = ref.split("/");
						attributes.put("href", title[title.length-1]);
					}else{
						attributes.put("href", ref);
					}
				}
			}
			attributes.put("type", type);
			attributes.put("identifier", identifier);
			//attributes.put("href", ref);
			if("imsldcontent".equals(type)){
				FileUploadBean fileUploadBean = fileUploadBeansResources.get(attributes.get("href"));
				attributes.put("file", fileUploadBean);
			}else{
				attributes.put("file", fileUploadBeansResources.get(ref));
			}
			resources.put(identifier, attributes);
		}


	}


	@RequestMapping(value="jsp/fileUpload/uploadLADescription.action" , method = RequestMethod.POST)
	protected @ResponseBody void onSubmitLADescription(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value="file") CommonsMultipartFile command,
			//@RequestParam(value="activityId") String activityId,
			HttpSession session) throws ServletException, IOException {
		String activityId = (String) session.getAttribute("graphId");
		String[] activityType = activityId.split(":");
		UnitOfLearning unitOfLearning = unitOfLearningService.get((Integer)session.getAttribute("unitOfLearningId"));

		List<FileUploadBean> fileUploadBeanSet = new ArrayList<FileUploadBean>();
		List<Activity> activitySet = new ArrayList<Activity>();
		FileUploadBean bean = new FileUploadBean();
		CommonsMultipartFile cmf = (CommonsMultipartFile)command;
		String fileName[] = cmf.getOriginalFilename().split(".");
		bean.setBytes(cmf.getBytes());
		bean.setName(cmf.getOriginalFilename());
		bean.setResourceType(ResourceType.LADESCRIPTION);
		bean.setSize(cmf.getSize());
		bean = fileUploadBeanService.save(bean);
		Activity activity;
		if("Activity".equals(activityType[0])){
			activity = new LearningActivity();
		}else {
			activity = new SupportActivity();
		}
		activity = activityService.getbyGraphId(activityType[1]);	
		if(activity==null){
			if("Activity".equals(activityType[0])){
				activity = new LearningActivity();
			}else {
				activity = new SupportActivity();
			}
			fileUploadBeanSet.add(bean);
			activity.setFiles(fileUploadBeanSet);
		}else {
			activity.addFiles(bean);
		}

		activity.setActivityGraphId(activityType[1]);
		activity = activityService.save(activity);
		//activitySet.add(activity);
		unitOfLearning.addActivity(activity);
		unitOfLearningService.saveOrUpdate(unitOfLearning);

		response.setContentType("text/html");
	}    



	@RequestMapping(value="jsp/fileUpload/viewLADescription.action" , method = RequestMethod.GET)
	protected @ResponseBody Map viewFilesLADescription(
			HttpServletRequest request,
			HttpServletResponse response,
			HttpSession session) throws ServletException, IOException {
		String activityId = (String) session.getAttribute("graphId");

		String[] activityType = activityId.split(":");
		UnitOfLearning unitOfLearning = unitOfLearningService.get((Integer)session.getAttribute("unitOfLearningId"));

		List<Activity> activities = unitOfLearning.getActivity();
		Map<String,Object> modelMap = new HashMap<String,Object>(3);
		List<FileUploadBean> files = new ArrayList<FileUploadBean>();
		List<FileUploadBean> viewFiles = new ArrayList<FileUploadBean>();
		for(Activity activity : activities){
			if(activityType[1].equals(activity.getActivityGraphId())){
				files = activity.getFiles();
				for(FileUploadBean file : files){
					if(file.getResourceType().equals(ResourceType.LADESCRIPTION)){
						viewFiles.add(file);
					}
				}
			}
		}
		for(FileUploadBean file : viewFiles){
			file.setBytes(null);
		}
		modelMap.put("items", viewFiles);
		modelMap.put("total", viewFiles.size());
		modelMap.put("success", true);

		return modelMap;
	}   


	@RequestMapping(value="jsp/fileUpload/delLADescription.action")
	protected @ResponseBody void deleteFilesLADescription(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value="del") Integer delId,
			HttpSession session) throws ServletException, IOException {

		String activityId = (String) session.getAttribute("graphId");
		System.out.println("activityId"+ activityId);
		String[] activityType = activityId.split(":");
		FileUploadBean fileToDelete = fileUploadBeanService.get(delId);
		Activity activity = activityService.getbyGraphId(activityType[1]);
		List<FileUploadBean> files = new ArrayList<FileUploadBean>();
		List<FileUploadBean> filesToAdd = new ArrayList<FileUploadBean>();
		files = activity.getFiles();
		for(int i = 0; i<files.size(); i++){
			if(fileToDelete.getId()!=(files.get(i).getId())){
				filesToAdd.add(files.get(i));
			}
		}
		activity.setFiles(filesToAdd);
		activityService.save(activity);

		fileUploadBeanService.remove(fileToDelete);
		Activity activityAfterDeletion = activityService.getbyGraphId(activityType[1]);
		files = activityAfterDeletion.getFiles();

		Map<String,Object> modelMap = new HashMap<String,Object>(3);

		for(FileUploadBean file : files){
			file.setBytes(null);
		}
		modelMap.put("items", files);
		modelMap.put("total", files.size());
		modelMap.put("success", true);
	}  


	@RequestMapping(value="jsp/fileUpload/downloadLADescription.action")
	protected @ResponseBody void downloadFilesLADescription(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value="download") Integer downloadId,
			HttpSession session) throws ServletException, IOException {

		FileUploadBean fileToDownload = fileUploadBeanService.get(downloadId);
		InputStream is = new ByteArrayInputStream(fileToDownload.getBytes());
		response.setContentType("application");
		response.addHeader("Content-Disposition", "attachment; filename=\""+fileToDownload.getName()+"\"");
		response.setContentLength(is.available());
		response.getOutputStream().write( inputStream2bytes(is) );


	}  

	@RequestMapping(value="jsp/fileUpload/uploadSADescription.action" , method = RequestMethod.POST)
	protected @ResponseBody void onSubmitSADescription(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value="file") CommonsMultipartFile command,
			//@RequestParam(value="activityId") String activityId,
			HttpSession session) throws ServletException, IOException {
		String activityId = (String) session.getAttribute("graphId");
		String[] activityType = activityId.split(":");
		UnitOfLearning unitOfLearning = unitOfLearningService.get((Integer)session.getAttribute("unitOfLearningId"));

		List<FileUploadBean> fileUploadBeanSet = new ArrayList<FileUploadBean>();
		List<Activity> activitySet = new ArrayList<Activity>();
		FileUploadBean bean = new FileUploadBean();
		CommonsMultipartFile cmf = (CommonsMultipartFile)command;
		String fileName[] = cmf.getOriginalFilename().split(".");
		bean.setBytes(cmf.getBytes());
		bean.setName(cmf.getOriginalFilename());
		bean.setResourceType(ResourceType.SADESCRIPTION);
		bean.setSize(cmf.getSize());
		bean = fileUploadBeanService.save(bean);
		Activity activity;
		if("Activity".equals(activityType[0])){
			activity = new LearningActivity();
		}else {
			activity = new SupportActivity();
		}
		activity = activityService.getbyGraphId(activityType[1]);	
		if(activity==null){
			if("Activity".equals(activityType[0])){
				activity = new LearningActivity();
			}else {
				activity = new SupportActivity();
			}
			fileUploadBeanSet.add(bean);
			activity.setFiles(fileUploadBeanSet);
		}else {
			activity.addFiles(bean);
		}

		activity.setActivityGraphId(activityType[1]);
		activity = activityService.save(activity);
		//activitySet.add(activity);
		unitOfLearning.addActivity(activity);
		unitOfLearningService.saveOrUpdate(unitOfLearning);

		response.setContentType("text/html");
	}    


	@RequestMapping(value="jsp/fileUpload/viewSADescription.action" , method = RequestMethod.GET)
	protected @ResponseBody Map viewFilesSADescription(
			HttpServletRequest request,
			HttpServletResponse response,
			HttpSession session) throws ServletException, IOException {
		String activityId = (String) session.getAttribute("graphId");

		String[] activityType = activityId.split(":");
		UnitOfLearning unitOfLearning = unitOfLearningService.get((Integer)session.getAttribute("unitOfLearningId"));

		List<Activity> activities = unitOfLearning.getActivity();
		Map<String,Object> modelMap = new HashMap<String,Object>(3);
		List<FileUploadBean> files = new ArrayList<FileUploadBean>();
		List<FileUploadBean> viewFiles = new ArrayList<FileUploadBean>();
		for(Activity activity : activities){
			if(activityType[1].equals(activity.getActivityGraphId())){
				files = activity.getFiles();
				for(FileUploadBean file : files){
					if(file.getResourceType().equals(ResourceType.SADESCRIPTION)){
						viewFiles.add(file);
					}
				}
			}
		}
		for(FileUploadBean file : viewFiles){
			file.setBytes(null);
		}
		modelMap.put("items", viewFiles);
		modelMap.put("total", viewFiles.size());
		modelMap.put("success", true);

		return modelMap;
	}   


	@RequestMapping(value="jsp/fileUpload/delSADescription.action")
	protected @ResponseBody void deleteFilesSADescription(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value="del") Integer delId,
			HttpSession session) throws ServletException, IOException {

		String activityId = (String) session.getAttribute("graphId");
		System.out.println("activityId"+ activityId);
		String[] activityType = activityId.split(":");
		FileUploadBean fileToDelete = fileUploadBeanService.get(delId);
		Activity activity = activityService.getbyGraphId(activityType[1]);
		List<FileUploadBean> files = new ArrayList<FileUploadBean>();
		List<FileUploadBean> filesToAdd = new ArrayList<FileUploadBean>();
		files = activity.getFiles();
		for(int i = 0; i<files.size(); i++){
			if(fileToDelete.getId()!=(files.get(i).getId())){
				filesToAdd.add(files.get(i));
			}
		}
		activity.setFiles(filesToAdd);
		activityService.save(activity);

		fileUploadBeanService.remove(fileToDelete);
		Activity activityAfterDeletion = activityService.getbyGraphId(activityType[1]);
		files = activityAfterDeletion.getFiles();

		Map<String,Object> modelMap = new HashMap<String,Object>(3);

		for(FileUploadBean file : files){
			file.setBytes(null);
		}
		modelMap.put("items", files);
		modelMap.put("total", files.size());
		modelMap.put("success", true);
	}  


	@RequestMapping(value="jsp/fileUpload/downloadSADescription.action")
	protected @ResponseBody void downloadFilesSADescription(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value="download") Integer downloadId,
			HttpSession session) throws ServletException, IOException {

		FileUploadBean fileToDownload = fileUploadBeanService.get(downloadId);
		InputStream is = new ByteArrayInputStream(fileToDownload.getBytes());
		response.setContentType("application");
		response.addHeader("Content-Disposition", "attachment; filename=\""+fileToDownload.getName()+"\"");
		response.setContentLength(is.available());
		response.getOutputStream().write( inputStream2bytes(is) );


	} 

	@RequestMapping(value="jsp/fileUpload/uploadLAObjective.action" , method = RequestMethod.POST)
	protected @ResponseBody void onSubmitLAObjective(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value="file") CommonsMultipartFile command,
			//@RequestParam(value="activityId") String activityId,
			HttpSession session) throws ServletException, IOException {
		String activityId = (String) session.getAttribute("graphId");
		String[] activityType = activityId.split(":");
		UnitOfLearning unitOfLearning = unitOfLearningService.get((Integer)session.getAttribute("unitOfLearningId"));

		List<FileUploadBean> fileUploadBeanSet = new ArrayList<FileUploadBean>();
		List<Activity> activitySet = new ArrayList<Activity>();
		FileUploadBean bean = new FileUploadBean();
		CommonsMultipartFile cmf = (CommonsMultipartFile)command;
		String fileName[] = cmf.getOriginalFilename().split(".");
		bean.setBytes(cmf.getBytes());
		bean.setName(cmf.getOriginalFilename());
		bean.setResourceType(ResourceType.LAOBJECTIVE);
		bean.setSize(cmf.getSize());
		bean = fileUploadBeanService.save(bean);
		Activity activity;
		if("Activity".equals(activityType[0])){
			activity = new LearningActivity();
		}else {
			activity = new SupportActivity();
		}
		activity = activityService.getbyGraphId(activityType[1]);	
		if(activity==null){
			if("Activity".equals(activityType[0])){
				activity = new LearningActivity();
			}else {
				activity = new SupportActivity();
			}
			fileUploadBeanSet.add(bean);
			activity.setFiles(fileUploadBeanSet);
		}else {
			activity.addFiles(bean);
		}

		activity.setActivityGraphId(activityType[1]);
		activity = activityService.save(activity);
		//activitySet.add(activity);
		unitOfLearning.addActivity(activity);
		unitOfLearningService.saveOrUpdate(unitOfLearning);

		response.setContentType("text/html");
	}    



	@RequestMapping(value="jsp/fileUpload/viewLAObjective.action" , method = RequestMethod.GET)
	protected @ResponseBody Map viewFilesLAObjective(
			HttpServletRequest request,
			HttpServletResponse response,
			HttpSession session) throws ServletException, IOException {
		String activityId = (String) session.getAttribute("graphId");

		String[] activityType = activityId.split(":");
		UnitOfLearning unitOfLearning = unitOfLearningService.get((Integer)session.getAttribute("unitOfLearningId"));

		List<Activity> activities = unitOfLearning.getActivity();
		Map<String,Object> modelMap = new HashMap<String,Object>(3);
		List<FileUploadBean> files = new ArrayList<FileUploadBean>();
		List<FileUploadBean> viewFiles = new ArrayList<FileUploadBean>();
		for(Activity activity : activities){
			if(activityType[1].equals(activity.getActivityGraphId())){
				files = activity.getFiles();
				for(FileUploadBean file : files){
					if(file.getResourceType().equals(ResourceType.LAOBJECTIVE)){
						viewFiles.add(file);
					}
				}
			}
		}
		for(FileUploadBean file : viewFiles){
			file.setBytes(null);
		}
		modelMap.put("items", viewFiles);
		modelMap.put("total", viewFiles.size());
		modelMap.put("success", true);

		return modelMap;
	}   


	@RequestMapping(value="jsp/fileUpload/delLAObjective.action")
	protected @ResponseBody void deleteFilesLAObjective(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value="del") Integer delId,
			HttpSession session) throws ServletException, IOException {

		String activityId = (String) session.getAttribute("graphId");
		System.out.println("activityId"+ activityId);
		String[] activityType = activityId.split(":");
		FileUploadBean fileToDelete = fileUploadBeanService.get(delId);
		Activity activity = activityService.getbyGraphId(activityType[1]);
		List<FileUploadBean> files = new ArrayList<FileUploadBean>();
		List<FileUploadBean> filesToAdd = new ArrayList<FileUploadBean>();
		files = activity.getFiles();
		for(int i = 0; i<files.size(); i++){
			if(fileToDelete.getId()!=(files.get(i).getId())){
				filesToAdd.add(files.get(i));
			}
		}
		activity.setFiles(filesToAdd);
		activityService.save(activity);

		fileUploadBeanService.remove(fileToDelete);
		Activity activityAfterDeletion = activityService.getbyGraphId(activityType[1]);
		files = activityAfterDeletion.getFiles();

		Map<String,Object> modelMap = new HashMap<String,Object>(3);

		for(FileUploadBean file : files){
			file.setBytes(null);
		}
		modelMap.put("items", files);
		modelMap.put("total", files.size());
		modelMap.put("success", true);
	}  


	@RequestMapping(value="jsp/fileUpload/downloadLAObjective.action")
	protected @ResponseBody void downloadFilesLAObjective(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value="download") Integer downloadId,
			HttpSession session) throws ServletException, IOException {

		FileUploadBean fileToDownload = fileUploadBeanService.get(downloadId);
		InputStream is = new ByteArrayInputStream(fileToDownload.getBytes());
		response.setContentType("application");
		response.addHeader("Content-Disposition", "attachment; filename=\""+fileToDownload.getName()+"\"");
		response.setContentLength(is.available());
		response.getOutputStream().write( inputStream2bytes(is) );


	}  

	@RequestMapping(value="jsp/fileUpload/uploadLAPrerequisite.action" , method = RequestMethod.POST)
	protected @ResponseBody void onSubmitLAPrerequisite(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value="file") CommonsMultipartFile command,
			//@RequestParam(value="activityId") String activityId,
			HttpSession session) throws ServletException, IOException {
		String activityId = (String) session.getAttribute("graphId");
		String[] activityType = activityId.split(":");
		UnitOfLearning unitOfLearning = unitOfLearningService.get((Integer)session.getAttribute("unitOfLearningId"));

		List<FileUploadBean> fileUploadBeanSet = new ArrayList<FileUploadBean>();
		List<Activity> activitySet = new ArrayList<Activity>();
		FileUploadBean bean = new FileUploadBean();
		CommonsMultipartFile cmf = (CommonsMultipartFile)command;
		String fileName[] = cmf.getOriginalFilename().split(".");
		bean.setBytes(cmf.getBytes());
		bean.setName(cmf.getOriginalFilename());
		bean.setResourceType(ResourceType.LAPREREQUISITES);
		bean.setSize(cmf.getSize());
		bean = fileUploadBeanService.save(bean);
		Activity activity;
		if("Activity".equals(activityType[0])){
			activity = new LearningActivity();
		}else {
			activity = new SupportActivity();
		}
		activity = activityService.getbyGraphId(activityType[1]);	
		if(activity==null){
			if("Activity".equals(activityType[0])){
				activity = new LearningActivity();
			}else {
				activity = new SupportActivity();
			}
			fileUploadBeanSet.add(bean);
			activity.setFiles(fileUploadBeanSet);
		}else {
			activity.addFiles(bean);
		}

		activity.setActivityGraphId(activityType[1]);
		activity = activityService.save(activity);
		//activitySet.add(activity);
		unitOfLearning.addActivity(activity);
		unitOfLearningService.saveOrUpdate(unitOfLearning);

		response.setContentType("text/html");
	}    



	@RequestMapping(value="jsp/fileUpload/viewLAPrerequisite.action" , method = RequestMethod.GET)
	protected @ResponseBody Map viewFilesLAPrerequisite(
			HttpServletRequest request,
			HttpServletResponse response,
			HttpSession session) throws ServletException, IOException {
		String activityId = (String) session.getAttribute("graphId");

		String[] activityType = activityId.split(":");
		UnitOfLearning unitOfLearning = unitOfLearningService.get((Integer)session.getAttribute("unitOfLearningId"));

		List<Activity> activities = unitOfLearning.getActivity();
		Map<String,Object> modelMap = new HashMap<String,Object>(3);
		List<FileUploadBean> files = new ArrayList<FileUploadBean>();
		List<FileUploadBean> viewFiles = new ArrayList<FileUploadBean>();
		for(Activity activity : activities){
			if(activityType[1].equals(activity.getActivityGraphId())){
				files = activity.getFiles();
				for(FileUploadBean file : files){
					if(file.getResourceType().equals(ResourceType.LAPREREQUISITES)){
						viewFiles.add(file);
					}
				}
			}
		}
		for(FileUploadBean file : viewFiles){
			file.setBytes(null);
		}
		modelMap.put("items", viewFiles);
		modelMap.put("total", viewFiles.size());
		modelMap.put("success", true);

		return modelMap;
	}   


	@RequestMapping(value="jsp/fileUpload/delLAPrerequisite.action")
	protected @ResponseBody void deleteFilesLAPrerequisite(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value="del") Integer delId,
			HttpSession session) throws ServletException, IOException {

		String activityId = (String) session.getAttribute("graphId");
		System.out.println("activityId"+ activityId);
		String[] activityType = activityId.split(":");
		FileUploadBean fileToDelete = fileUploadBeanService.get(delId);
		Activity activity = activityService.getbyGraphId(activityType[1]);
		List<FileUploadBean> files = new ArrayList<FileUploadBean>();
		List<FileUploadBean> filesToAdd = new ArrayList<FileUploadBean>();
		files = activity.getFiles();
		for(int i = 0; i<files.size(); i++){
			if(fileToDelete.getId()!=(files.get(i).getId())){
				filesToAdd.add(files.get(i));
			}
		}
		activity.setFiles(filesToAdd);
		activityService.save(activity);

		fileUploadBeanService.remove(fileToDelete);
		Activity activityAfterDeletion = activityService.getbyGraphId(activityType[1]);
		files = activityAfterDeletion.getFiles();

		Map<String,Object> modelMap = new HashMap<String,Object>(3);

		for(FileUploadBean file : files){
			file.setBytes(null);
		}
		modelMap.put("items", files);
		modelMap.put("total", files.size());
		modelMap.put("success", true);
	}  


	@RequestMapping(value="jsp/fileUpload/downloadLAPrerequisite.action")
	protected @ResponseBody void downloadFilesLAPrerequisite(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value="download") Integer downloadId,
			HttpSession session) throws ServletException, IOException {

		FileUploadBean fileToDownload = fileUploadBeanService.get(downloadId);
		InputStream is = new ByteArrayInputStream(fileToDownload.getBytes());
		response.setContentType("application");
		response.addHeader("Content-Disposition", "attachment; filename=\""+fileToDownload.getName()+"\"");
		response.setContentLength(is.available());
		response.getOutputStream().write( inputStream2bytes(is) );


	}  


	private byte[] inputStream2bytes(InputStream inStream) throws IOException {
		int fileSize = inStream.available();
		byte[] buffer = new byte[fileSize];
		inStream.read(buffer);
		return buffer;
	}

	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder)
			throws ServletException {
		// to actually be able to convert Multipart instance to byte[]
		// we have to register a custom editor
		binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
		// now Spring knows how to handle multipart object and convert them
	}

	public IFileUploadBeanService getFileUploadBeanService() {
		return fileUploadBeanService;
	}
	@Resource(name="fileUploadBeanService")
	public void setFileUploadBeanService(
			IFileUploadBeanService fileUploadBeanService) {
		this.fileUploadBeanService = fileUploadBeanService;
	}

	public IUnitOfLearningService getUnitOfLearningService() {
		return unitOfLearningService;
	}
	@Resource(name="unitOfLearningService")
	public void setUnitOfLearningService(
			IUnitOfLearningService unitOfLearningService) {
		this.unitOfLearningService = unitOfLearningService;
	}

	public IActivityService getActivityService() {
		return activityService;
	}
	@Resource(name="activityService")
	public void setActivityService(IActivityService activityService) {
		this.activityService = activityService;
	}

	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	@Resource(name="roleService")
	public void setRoleService(IRoleService roleService) {
		this.roleService = roleService;
	}

	@Resource(name="toolAndMaterialService")
	public void setToolAndMaterialService(
			IToolAndMaterialService toolAndMaterialService) {
		this.toolAndMaterialService = toolAndMaterialService;
	}
	
	@Resource(name="graphService")
	public void setGraphService(IGraphService graphService) {
		this.graphService = graphService;
	}

}